package com.lxj.api;

import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestHandle;
import com.loopj.android.http.RequestParams;
import com.lxj.model.UserInfo;
import com.lxj.network.http.HttpUtils;
import com.lxj.utils.PublicFunction;

public class UserApi {

	private static UserApi mInstance = null;

	public static UserApi getInstance() {
		if (null == mInstance) {
			mInstance = new UserApi();
		}
		return mInstance;
	}

	public RequestHandle getAllUser(final Context aContext, String aUserID,final OnUserDetailListener aOnUserDetailListener) {
		RequestParams params = ApiConfig.Detail(aUserID);

		RequestHandle t = HttpUtils.get(aContext, ApiConfig.getApiHost(),params, new AsyncHttpResponseHandler() {
					@Override
					public void onStart() {
						if (aOnUserDetailListener != null) {
							aOnUserDetailListener.onStart();
						}
					}

					@Override
					public void onFinish() {
						if (aOnUserDetailListener != null) {
							aOnUserDetailListener.onFinish();
						}
					}

					@Override
					public void onProgress(int bytesWritten, int totalSize) {

						if (aOnUserDetailListener != null) {
							aOnUserDetailListener.onProgress(bytesWritten,totalSize);
						}
					}

					@Override
					public void onSuccess(int statusCode, Header[] headers,byte[] aResponseData) {

						JSONObject responejsonbase = ApiUtils.getResponseJSON(headers, aResponseData);
						String resultCode = ApiUtils.parseResultCode(responejsonbase);

						if (resultCode == null|| resultCode.equals(ApiConfig.RESULT_CODE_SUCCESS)) {
							JSONObject responejson = ApiUtils.parseResultData(responejsonbase);
							JSONObject userinfo = PublicFunction.getJSONObject(responejson, "info");

							UserInfo userInfo = ApiUtils.parseUserInfo(userinfo);
							if (aOnUserDetailListener != null) {
								aOnUserDetailListener.onSuccess(userInfo);
							}
						} else {
							if (aOnUserDetailListener != null) {
								aOnUserDetailListener.onFailure(ApiUtils.getResponseCode(resultCode));
							}
						}
					}

					@Override
					public void onFailure(int statusCode, Header[] headers,byte[] errorResponse, Throwable e) {

						if (aOnUserDetailListener != null) {
							aOnUserDetailListener.onFailure(ApiUtils.getResponseCode(String.valueOf(statusCode)));
						}
					}
				});

		return t;
	}

}
